package org.exez.modules.visitor.controller;

import cn.hutool.http.HttpUtil;
import cn.hutool.json.JSON;
import cn.hutool.json.JSONUtil;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import io.swagger.annotations.*;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.StringUtils;
import org.apache.shiro.SecurityUtils;
import org.exez.common.api.vo.Result;
import org.exez.common.aspect.annotation.AutoLog;
import org.exez.common.exception.JeecgBootException;
import org.exez.common.system.base.controller.JeecgController;
import org.exez.common.system.vo.LoginUser;
import org.exez.common.util.DateUtils;
import org.exez.modules.visitor.constant.ApplicationStatusEnum;
import org.exez.modules.visitor.constant.AuthorityEnum;
import org.exez.modules.visitor.constant.IdentityTypeEnum;
import org.exez.modules.visitor.constant.VisitorConstants;
import org.exez.modules.visitor.dto.ReservationApplicationDTO;
import org.exez.modules.visitor.entity.ReservationApplication;
import org.exez.modules.visitor.service.IReservationApplicationService;
import org.exez.modules.visitor.util.AES;
import org.exez.modules.visitor.util.SignUtils;
import org.exez.modules.visitor.vo.IndexCountVO;
import org.exez.modules.visitor.vo.ReservationApplicationCountVO;
import org.exez.modules.visitor.vo.ReservationApplicationVO;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.format.annotation.DateTimeFormat;
import org.springframework.web.bind.annotation.*;

import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @Description: 访客申请记录表
 * @Author: exez-boot
 * @Date: 2020-06-04
 * @Version: V1.0
 */
@Slf4j
@Api(tags = "访客预约功能接口")
@RestController
@RequestMapping("/visitor/reservationApplication")
public class ReservationApplicationController extends JeecgController<ReservationApplication, IReservationApplicationService> {
    @Value("${url.file-view}")
    private String fileRootPath;

    @Autowired
    private IReservationApplicationService reservationApplicationService;


    /**
     * 拜访记录
     *
     * @param pageNo
     * @param pageSize
     * @return
     */
    @AutoLog(value = "拜访记录")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "startTime", value = "开始时间 :yyyy/MM/dd HH:mm:ss", required = false, dataType = "String", paramType = "query"),
            @ApiImplicitParam(name = "endTime", value = "结束时间:yyyy/MM/dd HH:mm:ss", required = false, dataType = "String", paramType = "query"),
            @ApiImplicitParam(name = "type", value = "进入方式1：车  2：人", required = false, dataType = "Integer", paramType = "query"),
            @ApiImplicitParam(name = "name", value = "姓名", required = false, dataType = "String", paramType = "query"),
            @ApiImplicitParam(name = "institutionId", value = "单位id", required = false, dataType = "Integer", paramType = "query"),
            @ApiImplicitParam(name = "pageNo", value = "页码", required = true, dataType = "Integer", paramType = "query"),
            @ApiImplicitParam(name = "pageSize", value = "页码大小", required = true, dataType = "Integer", paramType = "query"),
            @ApiImplicitParam(name = "timeType", value = "拜访时间类型（1：今日 2：历史  3：未到访）", required = true, dataType = "Integer", paramType = "query"),
            @ApiImplicitParam(name = "applicationStatus", value = "1:全部 2：未访 3：已访）", required = true, dataType = "Integer", paramType = "query"),
    })
    @ApiOperation(value = "拜访记录", notes = "拜访记录")
    @GetMapping(value = "/listApplicationByToday")
    public Result<ReservationApplicationCountVO> listApplicationByToday(
            @RequestParam(name = "startTime", required = false) @DateTimeFormat(pattern = "yyyy/MM/dd HH:mm:ss") Date startTime,
            @RequestParam(name = "endTime", required = false) @DateTimeFormat(pattern = "yyyy/MM/dd HH:mm:ss") Date endTime,
            @RequestParam(name = "type", required = false) Integer type,
            @RequestParam(name = "name", required = false) String name,
            @RequestParam(name = "institutionId", required = false) Integer institutionId,
            @RequestParam(name = "pageNo", defaultValue = "1") Integer pageNo,
            @RequestParam(name = "pageSize", defaultValue = "10") Integer pageSize,
            @RequestParam(name = "timeType", defaultValue = "1") Integer timeType,
            @RequestParam(name = "applicationStatus", defaultValue = "1") Integer applicationStatus) {
        Result<ReservationApplicationCountVO> result = new Result<>();

        Page<ReservationApplication> page = new Page<>(pageNo, pageSize);
        LambdaQueryWrapper<ReservationApplication> queryWrapper = new LambdaQueryWrapper<>();
        LoginUser sysUser = (LoginUser) SecurityUtils.getSubject().getPrincipal();
        if (null != institutionId) {
            queryWrapper.eq(ReservationApplication::getRespondentInstitutionId, institutionId);
        } else if (!AuthorityEnum.ONE_USER.getIndex().equals(sysUser.getAuthority())) {
            queryWrapper.in(ReservationApplication::getRespondentInstitutionId, AES.integerList(sysUser.getInstitutionId()));
        }

        if (null != type && type == 2) {
            queryWrapper.isNull(ReservationApplication::getNumberPlate).or().eq(ReservationApplication::getNumberPlate, "");
        } else if (null != type && type == 1) {
            queryWrapper.isNotNull(ReservationApplication::getNumberPlate).ne(ReservationApplication::getNumberPlate, "");
        }

        queryWrapper.like(StringUtils.isNotBlank(name), ReservationApplication::getName, name);

        //条件添加
        if (timeType == 1) {
            if (null != startTime && null != endTime) {
                if (startTime.getTime() > endTime.getTime()) {
                    throw new JeecgBootException("开始时间大于结束时间");
                }
            } else {
                startTime = DateUtils.getStartTime();
                endTime = DateUtils.getEndTime();
            }
            queryWrapper.between(ReservationApplication::getVisitDate, startTime, endTime);
        } else if (timeType ==2){
            if (null != startTime && null != endTime) {

                if (startTime.getTime() > endTime.getTime()) {
                    throw new JeecgBootException("开始时间大于结束时间");
                }
                queryWrapper.between(ReservationApplication::getVisitDate, startTime, endTime);
            } else {
                queryWrapper.lt(ReservationApplication::getVisitDate, DateUtils.getStartTime());
            }

            queryWrapper.in(ReservationApplication::getStatus, 2, 3, 5);
        } else {
            queryWrapper.ge(ReservationApplication::getVisitDate, DateUtils.getStartTimeByDay(new Date(),1));
            queryWrapper.eq(ReservationApplication::getStatus, ApplicationStatusEnum.SQTG.getIndex());
        }

        ReservationApplicationCountVO reservationApplicationCountVO = reservationApplicationService.listApplication(page, queryWrapper, applicationStatus,timeType);

        result.successSetDate(reservationApplicationCountVO);
        return result;
    }

    /**
     * 即将到访信息
     *
     * @return
     */
    @AutoLog(value = "即将到访信息")
    @ApiOperation(value = "即将到访信息", notes = "即将到访信息")
    @GetMapping(value = "/listApplicationByComingSoon")
    public Result<List<ReservationApplicationVO>> listApplicationByComingSoon(@RequestParam(name = "pageSize",
            required = false, defaultValue = "4") Integer pageSize) {

        Result<List<ReservationApplicationVO>> result = new Result<>();

        List<ReservationApplicationVO> reservationApplicationVOS = reservationApplicationService.listApplicationByComingSoon(pageSize);

        result.successSetDate(reservationApplicationVOS);
        return result;
    }

    /**
     * 现场实时信息
     *
     * @return
     */
    @AutoLog(value = "现场实时信息")
    @ApiOperation(value = "现场实时信息", notes = "现场实时信息")
    @GetMapping(value = "/listApplicationByRealTime")
    public Result<List<ReservationApplicationVO>> listApplicationByRealTime(@RequestParam(name = "pageSize",
            required = false, defaultValue = "4") Integer pageSize) {

        Result<List<ReservationApplicationVO>> result = new Result<>();

        List<ReservationApplicationVO> reservationApplicationVOS = reservationApplicationService.listApplicationByRealTime(pageSize);

        result.successSetDate(reservationApplicationVOS);
        return result;
    }


    /**
     * 拜访查看详情
     *
     * @param id
     * @return
     */
    @AutoLog(value = "拜访查看详情")
    @ApiOperation(value = "拜访查看详情", notes = "拜访查看详情")
    @ApiResponses({@ApiResponse(code = 200, message = "OK", response = ReservationApplicationDTO.class),})
    @GetMapping(value = "/getDetailsById")
    public Result<ReservationApplicationDTO> getDetailsById(@RequestParam(name = "id", required = true) Integer id) {

        Result<ReservationApplicationDTO> result = new Result<>();
        ReservationApplicationDTO detailsById = reservationApplicationService.getDetailsById(id);

        result.successSetDate(detailsById);
        return result;
    }


    /**
     * 首页数字统计
     *
     * @return
     */
    @AutoLog(value = "首页数字统计")
    @ApiOperation(value = "首页数字统计", notes = "首页数字统计")
    @GetMapping(value = "/indexCount")
    public Result<IndexCountVO> indexCount() {
        Result<IndexCountVO> result = new Result<>();
        IndexCountVO indexCountVO = reservationApplicationService.indexCount();

        result.successSetDate(indexCountVO);
        return result;
    }


    /**
     * 数据分析--来访人员已到未到柱形图
     *
     * @return
     */
    @AutoLog(value = "数据分析--来访人员已到未到柱形图")
    @ApiOperation(value = "数据分析--来访人员已到未到柱形图", notes = "数据分析--来访人员已到未到柱形图")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "type", value = "统计类型：1周 2月 3年", required = true, dataType = "Integer", paramType = "query"),
            @ApiImplicitParam(name = "institutionId", value = "单位id", required = false, dataType = "Integer", paramType = "query")
    })
    @GetMapping(value = "/indexVisitorAnalysis")
    public Result<List<Map<String, String>>> indexVisitorAnalysis(@RequestParam(name = "type", defaultValue = "1") Integer type,
                                                                  @RequestParam(name = "institutionId", required = false) Integer institutionId) {
        Result<List<Map<String, String>>> result = new Result<>();
        List<Map<String, String>> maps = reservationApplicationService.indexVisitorAnalysis(type,institutionId);
        result.successSetDate(maps);
        return result;
    }


    /**
     * 首页来访人员已到未到柱形图
     *
     * @return
     */
    @AutoLog(value = "首页来访人员已到未到柱形图")
    @ApiOperation(value = "首页来访人员已到未到柱形图", notes = "首页来访人员已到未到柱形图")
    @ApiImplicitParam(name = "institutionId", value = "单位id", required = false, dataType = "Integer", paramType = "query")
    @GetMapping(value = "/indexVisitorAnalysisByDay")
    public Result<List<Map<String, String>>> indexVisitorAnalysisByDay(@RequestParam(name = "institutionId", required = false) Integer institutionId) {
        Result<List<Map<String, String>>> result = new Result<>();
        List<Map<String, String>> maps = reservationApplicationService.indexVisitorAnalysisByDay(institutionId);
        result.successSetDate(maps);
        return result;
    }

    /**
     * 测试数据发送
     *
     * @return
     */
    @ApiOperation(value = "测试数据发送", notes = "测试数据发送")
    @PostMapping(value = "/testpush")
    public Result<?> testpush(@RequestBody List<ReservationApplicationDTO> reservationApplicationDTOs) {

        JSON parse = JSONUtil.parse(reservationApplicationDTOs);

        String result = HttpUtil.createPost("http://10.19.63.10:1315/exea-admin/api/visitor/dataTransmission").body(parse).execute().body();

        log.info("[{}]result++", result);
        return Result.ok();
    }



    /**
     * testCode
     *
     * @return
     */
    @ApiOperation(value = "testCode", notes = "testCode")
    @GetMapping(value = "/testCode")
    public void testCode() {

        Result<Boolean> result = new Result<>();

        Map<String, String> map = new HashMap<>(16);
        map.put("identityValue", "360732199702032333");
        map.put("identityType", IdentityTypeEnum.IDENTITY_CARD.getName());
        map.put("name", "邓通明");
        map.put("mobile", "15970715061");
        map.put("token", VisitorConstants.token);
        map.put("timestamp", String.valueOf(DateUtils.getMillis()));
        String sign = SignUtils.createSign(map, VisitorConstants.key);
        map.put("sign", sign);


        String connectResult = HttpUtil.createPost(VisitorConstants.URL).body(JSONUtil.parse(map)).header("Content-Type", "application/json").execute().body();


        System.out.println(connectResult);


        JSONObject object = JSONArray.parseObject(connectResult);
        Integer code = object.containsKey("code") ? Integer.parseInt(object.getString("code")) : -1;
        if (code.equals(200)) {
            String data = object.containsKey("data") ? object.getString("data") : null;
            if (StringUtils.isNotBlank(data)) {
                JSONObject jsonObject = JSONArray.parseObject(data);
                String jmt = jsonObject.containsKey("jkm") ? jsonObject.getString("jkm") : null;
                if ("green".equals(jmt)) {
                    return;
                }
                throw new JeecgBootException("您不是绿码，预约失败");
            }
            throw new JeecgBootException("预约失败");
        }
        throw new JeecgBootException("预约失败:" + code);

    }


}
